<?php
declare (strict_types = 1);
namespace app\service;

use app\common\Service;

/**
 * 跨应用公共业务逻辑
 */
class SettingsService extends Service
{
    public function getSettings(string $name = '')
    {
        $settings = [];
        $list = $this->db->name('settings')->cache('settings')->select();
        foreach ($list as $l) {
            $settings[strtolower($l['name'])] = unserialize($l['value']);
        }
        if (empty($name)) {
            return $settings;
        }
        $name = explode(',', strtolower(trim($name, ',')));
        $count = count($name);
        if ($count > 1) {
            $result = [];
            foreach ($name as $k => $n) {
                $result[$n] = isset($settings[$n]) ? $settings[$n] : '';
            }
            return $result;
        } else if ($count == 1) {
            return isset($settings[$name[0]]) ? $settings[$name[0]] : '';
        } else {
            return '';
        }
    }

    public function saveSettings($name = '', $value = '')
    {
        if (is_array($name)) {
            foreach ($name as $k => $v) {
                $this->saveSettings($k, $v);
            }
            return;
        }
        if (!is_string($name)) {
            return;
        }
        $this->db->name('settings')->cache('settings')->replace()->insert([
            'name' => strtolower($name),
            'value' => serialize($value),
        ]);
    }
}
